import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Table } from 'antd';
import { subscribeComp } from '@/services/bajaService';

class DataTable extends Component {

  static defaultProps = {
    pageSize: 10
  }

  constructor(props) {
    super(props);
    this.columns = []
    this.title = ''
    this.pageNo = 1
    this.total = 0
    this.list = []
    this.realtimes = {}
    this.subs = []
    const { dataSource } = this.props;
    if(dataSource && dataSource.rows && dataSource.rows.length && dataSource.rows[0].cells) {
      this.title = dataSource.title;
      const width = 100/dataSource.rows[0].cells.length;
      const last = 100 - (dataSource.rows[0].cells.length-1)*width;
      this.total = dataSource.rows.length-1;
      this.columns = dataSource.rows[0].cells.map((cell, idx) => ({
        title: cell.title,
        dataIndex: 'di' + (idx+1),
        key: 'k' + (idx+1),
        width: (idx<dataSource.rows[0].cells.length-1)?width+'%':last+'%',
      }));
      dataSource.rows.forEach((row, idx) => {
        if(idx > 0) {
          const { cells } = row;
          const cell = { key: idx};
          cells.forEach((c,i) => {
            let value = ''
            if(c.cellType == 'TEXT') {
              value = c.title;
            } else if(c.cellType == 'REALTIME') {
              value = c.realtimeOrd;
              if(!this.realtimes[value]) {
                this.realtimes[value] = [];
              }
              this.realtimes[value].push((idx-1)+'|'+'di' + (i+1));
              value = '';
            }
            cell['di' + (i+1)] = value;
            cell['cellType'] = c.cellType;
          })
          this.list.push(cell);
        }
      });
    }
  }

  // handlePageChange = (changePageNo) => {
  //
  // }

  updateData = (value, ord) => {
    // console.log("updateData", value, ord, this.realtimes[ord]);
    if(this.realtimes[ord] && this.realtimes[ord].length > 0) {
      this.realtimes[ord].forEach(idxs => {
        const idx = idxs.split('|');
        this.list[idx[0]][idx[1]] = value;
        this.forceUpdate();
      })
    }
  }

  subscribeData = () => {
    const { realtimes } = this;
    if(realtimes) {
      Object.keys(realtimes).forEach(ord => {
        subscribeComp(ord, (component)=>{
          const value = parseFloat(component.getOut().getValue().toFixed(2));
          this.updateData(value, ord);
        }).then((sub)=> {
          this.subs.push(sub);
        });
      });
    }
  }

  componentDidMount() {
    this.subscribeData();
  }

  componentWillUnmount() {
    if(this.subs.length > 0) {
      this.subs.forEach(sub => {
        if(sub && sub.unsubscribeAll) {
          sub.unsubscribeAll();
          sub.detach();
        }
      })
      this.subs = []
    }
  }

  render() {
    const { title, list, pageNo, total, columns, realtimes } = this;
    // const { pageSize } = this.props;
    // console.log("DataTable render", list, realtimes);
    return (
      <Table
        title = {()=>title}
        className={'table-wrapper'}
        bordered={true}
        columns={columns}
        dataSource={list}
        rowKey='_id'
        pagination={{
          total,
          pageSize: total,
          current: pageNo,
          // onChange: this.handlePageChange,
        }}
      />
    );
  }
}

DataTable.propTypes = {
  dataSource: PropTypes.object.isRequired,
  pageSize: PropTypes.number
}

export default DataTable;
